//
//  WDBusinessManagerViewController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/30.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDBusinessManagerController.h"
#import "WDBusinessCell.h"
#import "WDBusiness.h"
#import "WDPhoneAlertView.h"
#import "WDLinkData.h"
#import "WDFirstSort.h"
#import "WDBusinessDetailController.h"

@interface WDBusinessManagerController () <UITableViewDelegate, UITableViewDataSource, WDBusinessCellDelegate>
/** 商户数据 */
@property (nonatomic, strong) NSArray *businessArr;
/** 商户排序数据 */
@property (nonatomic, strong) NSArray *dataArr;
/** 跟进人信息 */
@property (nonatomic, strong) NSMutableArray<WDLinkData *> *linkData;
/** 创建视图 */
@property (nonatomic, strong) UIView *creatView;
/** 创建按钮 */
@property (strong, nonatomic) UIButton *creatBtn;
/** 商户tableView */
@property (nonatomic, strong) UITableView *businessTableView;
@end

static NSString *cellID = @"placeCell";

@implementation WDBusinessManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WDBackColor;
    
    [self loadNavItemWithLeftAction:@selector(clickNavLeftBtn) leftBtnImage:@"actionbar" leftBtnSelImage:@"actionbar" title:@"商户维系" rihgtAction:@selector(clickNavRightBtn) rightBtnImage:nil rightBtnSelImage:nil];
    
    [self loadBusinessTableView];
    
    //获取数据
    [self sendRequest];
    
    //验证权限  
    if ([WDVerify verifyStr:supplier_create inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]]) {
        
        [self loadAddBtn];
        
        [self loadCreatView];
        self.creatBtn.hidden = NO;
        
    } else {
        
        [self loadCreatView];
        self.creatBtn.hidden = YES;
    }
    
    //加载图
    self.placeView = [self loadPlaceViewWithImageName:@"icon_loading" status:@"努力加载中..."];
    
}



- (void)loadBusinessTableView
{
    UITableView *businessTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    
    businessTableView.dataSource = self;
    
    businessTableView.delegate = self;
    
    //设置索引字体颜色
    businessTableView.sectionIndexColor = ColorForRGB(0x6b6b6b);
    //设置索引背景颜色
    businessTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    businessTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    
    businessTableView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:businessTableView];
    
    //注册占位cell
    [businessTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    
    self.businessTableView = businessTableView;
    
    [businessTableView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.right.equalTo(-10);
        make.top.bottom.equalTo(0);
    }];
}

/** 添加按钮 */
- (void)loadAddBtn
{
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.backgroundColor = ColorForRGB(0x4a90e2);
    [addBtn setImage:[UIImage imageNamed:@"icon-tianjiazhaopian"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(clickAddBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:addBtn];
    
    [addBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(-30);
        make.width.height.equalTo(60);
    }];
    
    //加阴影效果
    addBtn.layer.cornerRadius = 30.0;
    
    addBtn.layer.shadowOffset = CGSizeMake(1, 1);
    
    addBtn.layer.shadowOpacity = 0.8;
    
    addBtn.layer.shadowColor = [UIColor blackColor].CGColor;
}

/** 新建贷款视图 */
- (void)loadCreatView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = WDBackColor;
    [self.view addSubview:view];
    view.hidden = YES;
    self.creatView = view;
    
    //图标
    UIImageView *iconImage = [[UIImageView alloc] init];
    iconImage.image = [UIImage imageNamed:@"icon_loadFailed"];
    [view addSubview:iconImage];
    [iconImage makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(100);
        make.centerX.equalTo(view.centerX);
        make.height.equalTo(88);
        make.width.equalTo(103);
    }];
    
    //文字
    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = @"目前没有贷款申请";
    descLabel.textColor = ColorForRGB(0xaaaaaa);
    descLabel.font = [UIFont systemFontOfSize:15];
    descLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:descLabel];
    [descLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImage.bottom).offset(15);
        make.centerX.equalTo(view.centerX);
    }];
    
    //创建按钮
    UIButton *createBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    createBtn.backgroundColor = WDNavSeleColor;
    [createBtn setTitle:@"马上创建" forState:UIControlStateNormal];
    createBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    createBtn.layer.cornerRadius = 4;
    createBtn.clipsToBounds = YES;
    [createBtn setTitleColor:ColorForRGB(0xffffff) forState:UIControlStateNormal];
    [createBtn addTarget:self action:@selector(createClick) forControlEvents:UIControlEventTouchUpInside];
    self.creatBtn = createBtn;
    [view addSubview:createBtn];
    [createBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(descLabel.bottom).offset(26.5);
        make.width.equalTo(100);
    }];
    
}

#pragma mark - 发送网络请求
- (void)sendRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"business_time_stam"];
    
    time_stamp = (time_stamp == nil ? @"" : time_stamp);
    
    NSDictionary *parameters = @{
                                 @"time_stam":time_stamp,
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListSupplier];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self hideLoadView];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        //保存时间戳
        [userDefault setObject:responseObject[@"time_stam"] forKey:@"business_time_stam"];
        
        NSArray *tempArr = [WDBusiness mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        //排好序的商户数组
        self.businessArr = [tempArr sortedArrayUsingComparator:^NSComparisonResult(WDBusiness *obj1, WDBusiness *obj2) {
            return [obj1.start_with compare:obj2.start_with];
        }];
        
        //分组成字典数组
        self.dataArr = [WDFirstSort firstSortWithObjectArray:self.businessArr];
        
        [self.businessTableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"加载失败"];
        
    }];
}

#pragma mark - 按钮点击
- (void)clickNavLeftBtn
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@PostString object:NSStringFromClass([self class])];
     [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

//管理按钮
- (void)clickNavRightBtn
{
    
}

//添加
- (void)clickAddBtn:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if (sender.selected) {//旋转
        
        [UIView animateWithDuration:0.07 animations:^{
            
            sender.transform = CGAffineTransformMakeRotation(M_PI / 4);
            
        }];
        
    } else {//回复
        
        [UIView animateWithDuration:0.07 animations:^{
            
            sender.transform = CGAffineTransformMakeRotation(0);
            
        }];
        
    }
}

//创建
- (void)createClick
{
    
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dict = self.dataArr[section];
    NSMutableArray *array = dict[@"content"];
    return array.count * 2 - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 1) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        
        [cell.contentView setAlpha:0];
        
        cell.backgroundColor = [UIColor clearColor];
        
        cell.userInteractionEnabled = NO;
        
        return cell;
        
    } else {
        
        WDBusinessCell *cell = [WDBusinessCell businessCellWithTableView:tableView];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSDictionary *dict = self.dataArr[indexPath.section];
        NSArray *businessArray  = dict[@"content"];
        cell.business = businessArray[indexPath.row / 2];
        
        cell.delegate = self;
        
        self.linkData = (NSMutableArray *)cell.business.link_data;
        
        if ([self.linkData count]) {
            
            cell.linkData = self.linkData[0];
            
        }
        return cell;
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 1) {
        
        return 10;
        
    } else {
        
        return 130;
    }
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSDictionary *dict in self.dataArr) {
        NSString *title = dict[@"firstLetter"];
        [resultArray addObject:title];
    }
    return resultArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //商户详情
    WDBusinessDetailController *tempVC = [[WDBusinessDetailController alloc] init];
    
    NSDictionary *dict = self.dataArr[indexPath.section];
    NSMutableArray *businesses = dict[@"content"];
    
    tempVC.business = businesses[indexPath.row];
    
    tempVC.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempVC animated:YES];
    
}

#pragma mark - <WDBusinessDelegate>
- (void)callPhoneWithPhoneNumber:(NSString *)phoneNumber
{
    WDPhoneAlertView *alertView = [[WDPhoneAlertView alloc] initWithTitle:@"呼叫" message:phoneNumber sureBtn:@"呼叫" cancleBtn:@"取消"];
    
    alertView.resultIndex = ^(NSInteger index){
        
        NSURL *openURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]];
        
        [[UIApplication sharedApplication] openURL:openURL];
        
    };
    
    [alertView show];
}

@end
